import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import Icon from '../../component/Icon';
import { useTranslation } from 'react-i18next';
import { lastChannelInfo, readChannelInfo } from '../../service';
import Telegram from '../../utils/telegram'
import gtag from '../../google/analytics';
import { GtagEvent } from '../../google/analytics/Event';


const Container = styled.div`
    background-color: ${(prop) => prop.theme.background.box};
    padding: .75rem .75rem .8125rem;
    box-sizing: border-box;
    box-shadow: 0px 1px 10px 0px rgba(0,111,255,0.5);
    border-radius: 10px;
`

const Header = styled.div`
    display: flex;
    align-items: center;
    justify-content: start;
`
const Content = styled.div`
    color: '#A4A8AF';
    font-size: .75rem;
    text-align: start;
    margin-top: .6875rem;
    min-height: 1.25rem;
    overflow: hidden; 
    text-overflow: ellipsis;
    display: -webkit-box; 
    /*! autoprefixer: ignore next */
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    box-sizing: border-box;
`
const Title = styled.div`
    font-weight: bold;
    font-size: .875rem;
    color: #FFFFFF;
    margin-left: .6875rem;
    flex: 1;
    text-align: start;
`

const Dot = styled.div`
    width: 8px;
    height: 8px;
    background: #FF5867;
    border-radius: 50%;
    margin-top: -2px;
`

const Channel: React.FC = React.memo(() => {
    const { t } = useTranslation()

    const [show, setShow] = useState(false);
    const [text, setText] = useState('')
    const [id, setId] = useState<string>()

    const fetchData = useCallback(async () => {
        const res = await lastChannelInfo();
        if (!res.success) {
            return
        }
        setShow(Boolean(res.data?.newCount))
        setText(res.data?.text || '')
        setId(res.data?.messageId)
    }, [])

    useEffect(() => {
        fetchData()
    }, [fetchData])

    const onClick = () => {
        gtag.event(GtagEvent.Read, { is_new: show })
        Telegram.joinChannel();
        if (show) {
            fetchData();
            id && readChannelInfo({ messageId: id })
        }
    }
    return <Container onClick={onClick}>
        <Header>
            <Icon
                name='home_chat'
                width='22px'
            />
            <Title>{t('home.channelTitle')}</Title>
            {show && <Dot />}
        </Header>
        <Content>{text}</Content>
    </Container>
})

export default Channel;